package il.ac.braude.sona.control;

import il.ac.braude.sona.constants.Mssg;
import il.ac.braude.sona.constants.P;
import il.ac.braude.sona.constants.Resources;
import il.ac.braude.sona.constants.TestingParamKit;
import il.ac.braude.sona.entities.ExtensionRequest;
import il.ac.braude.sona.gui.forms.FormFrame;
import il.ac.braude.sona.gui.forms.FormListener;
import il.ac.braude.sona.gui.forms.myforms.ExtensionRequestsApproveForm;
import il.ac.braude.sona.gui.forms.myforms.RequestExtensionForm;
import il.ac.braude.sona.ocsf.client.Client;
import il.ac.braude.sona.ocsf.client.ServerResponseListener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JOptionPane;
/**
 * The ExtensionsController conatins methods to create and view extension requests
 * 
 * @author  Ofek Ron
 * @author Avihay Avitan
 * @author Nitzan Inbar
 * @author Sasha Rozenthal
 * Laboratory in Software Engineering,Ort Braude College.</p>
 *
 */
public class ExtensionsController implements FormListener , ActionListener {
	public String req_id,req_status,req_owner;
	private RequestExtensionForm form;
	private ExtensionRequestsApproveForm approveForm;
	public ArrayList<ExtensionRequest> values ;
	public ExtensionRequest testingExtensionRequest;
	private ArrayList<Integer> accepted = new ArrayList<Integer>();
	private JButton buttonToHide;
	private TestingParamKit myKit=TestingParamKit.getTestingKit();
	public int testrequestindex = 0;
/**
 * executes extension form
 * @param req_id
 * @param req_status
 * @param req_owner
 * @param jButton 
 */
	public void execExtensionForm(String req_id, String req_status, String req_owner, JButton jButton) {
		this.req_id = req_id;
		this.req_status = req_status;
		this.req_owner = req_owner;
		this.buttonToHide=jButton;
		String checkValid = checkValidExtension(req_id,req_status); 
		if(checkValid.equals(Resources.Strings.ValidExtension)) {
			form = new RequestExtensionForm(Resources.Strings.reqExtension,"Submit");
			form.addFormListener(this);
			form.showFrame();
		}
		else if (checkValid.equals(Resources.Strings.reqGranted))
			JOptionPane.showMessageDialog(null, checkValid);
		else if(checkValid.equals(Resources.Strings.DaysNotValid))
			JOptionPane.showMessageDialog(null, checkValid);
	}
	@Override
	public void onFormCanceled(FormFrame formFrame) {
		if (formFrame == this.form){
			form=null;
		}
		if (formFrame == this.approveForm){
			approveForm=null;
			accepted.clear();
		}

	}

	@Override
	public void onFormSubmited(FormFrame formFrame, ArrayList<Object> values) {

		if (formFrame == this.form)
			execRequestExtension(values);
		if (formFrame == this.approveForm)
			execApproveRequest(values);
	}
	private void execApproveRequest(ArrayList<Object> values) {
		approveForm.dispose();
		accepted.clear();
	}

	public String checkValidExtension(String req_id, String req_status)
	{
		return Resources.Strings.ValidExtension;


	}
	public void execRequestExtension(ArrayList<Object> values) {
		if (values.contains("")) {
			if (myKit.TestMode) {
				myKit.inDatabase = false;
				myKit.notifyTester();
			}
			else
			form.showMessege(P.fieldsError);
		}
		else
		{
			if (myKit.TestMode) {
			myKit.mailSent = false;
			myKit.inDatabase = false;
			}
			else {
			values.add(this.req_id);
			values.add(this.req_status);
			values.add(this.req_owner);
			}
			try {
				Client c = Client.getInstance();
				Mssg mssg = new Mssg(P.RequestExtension,values);

				c.sendToServer(new ServerResponseListener() {
					@Override
					public void onServerResponse(Mssg mssg) {
						if (mssg.is((P.error))) {
							form.showMessege((String) mssg.getMessege());
							return;
						}
						if (myKit.TestMode){
							myKit.inDatabase = true;
							myKit.mailSent = true;
							 myKit.extensionDecision = "No Decision";
							myKit.notifyTester();
							return;
						}
							else
							{
					
						JOptionPane.showMessageDialog(form,Resources.Strings.RequestIssued);
						form.dispose();
						buttonToHide.setVisible(false);
							}	}
				},mssg);
					
			} catch (Exception e) {
				form.showMessege(Resources.Strings.ConnectFailed);
			}

		}
	}
	public void execViewExtensionlist() {
		try  {
			Mssg mssg = new Mssg(P.extension);
			Client.getInstance().sendToServer(new ServerResponseListener() {
				@SuppressWarnings("unchecked")
				@Override
				public void onServerResponse(Mssg mssg) {
					if (mssg.is(P.error)) {
						JOptionPane.showMessageDialog(null,
								mssg.getMessege());
						return;
					}
					if(((values = new ArrayList<ExtensionRequest>((ArrayList<ExtensionRequest>)mssg.getMessege())) != null))
					{
						if (values.size() != 0)
						{
							approveForm = new ExtensionRequestsApproveForm(Resources.Strings.ExtensionRequests,"Finish",values);
							approveForm.addFormListener(ExtensionsController.this);
							approveForm.getBox().addActionListener(ExtensionsController.this);
							approveForm.addButton("Approve",  ExtensionsController.this);
							approveForm.addButton("Decline",  ExtensionsController.this);
							if (myKit.TestMode) {
								myKit.notifyTester();	
							}
							else
							approveForm.showFrame();
						}
						else
						{JOptionPane.showMessageDialog(null,
								String.format("No pending requests"));
					//	approveForm.dispose();
						return;
						}
					}
					else   
					{JOptionPane.showMessageDialog(null,
							String.format("Try again later"));
					approveForm.dispose();
					}
				}

			}
			, mssg);
		} catch (Exception e) {

			JOptionPane.showMessageDialog(null,
					String.format("Request Error"));
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if ((e.getActionCommand().equals("Approve"))||e.getActionCommand().equals("Decline"))
		{
			accepted.add(approveForm.getBox().getSelected());
			if (myKit.TestMode)
				testrequestindex = approveForm.getBox().getSelected();
			execApproveRequestHandle((values.get(approveForm.getBox().getSelected())).values,e.getActionCommand());
		}
		else
		{
			if (accepted.contains(approveForm.getBox().getSelected()))
				approveForm.buttonpanel.setVisible(false);
			else
				approveForm.buttonpanel.setVisible(true);
			approveForm.changeAnswer(values.get(approveForm.getBox().getSelected()));
		}
		approveForm.pack();
		approveForm.repaint();
	}
	public void execApproveRequestHandle(final HashMap<String, String> values2,final String decision) {
		try {
			if (myKit.TestMode)
				myKit.extensionDecision = "No Decision";
			values2.put("decision", decision);
			Client c = Client.getInstance();
			Mssg mssg = new Mssg(P.ExtensionDecision,values2);

			c.sendToServer(new ServerResponseListener() {
				@Override
				public void onServerResponse(Mssg mssg) {
                    if (myKit.TestMode) {
                    	myKit.extensionDecision = decision;
                    	approveForm.buttonpanel.setVisible(false);
    					approveForm.requestCount-- ;
    						approveForm.dispose();
    						myKit.notifyTester();
                    }
                    else
                    {
					if (mssg.is((P.error))) {
						approveForm.showMessege((String) mssg.getMessege());
						return;
					}
					JOptionPane.showMessageDialog(approveForm,P.UpdateComplete);
					approveForm.buttonpanel.setVisible(false);
					if(--approveForm.requestCount == 0) {
						JOptionPane.showMessageDialog(approveForm, "No more pending requests");
						approveForm.dispose();
					}
				}}
			},mssg);
		} catch (Exception e) {
			approveForm.showMessege(Resources.Strings.ConnectFailed);
		}

	}
	public int index() {
		return testrequestindex;
	}
}







